package com.example.demo.socket;

import com.example.demo.servlet.HttpMeServlet;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;

/**
 * @author maxf
 * @version 1.0
 * @ClassName MyTomcat
 * @Description
 * @date 2019/2/13 15:59
 */
public class MyTomcat {
    private static final int port = 8099;
    //使用map装载servlet的信息
    public static final HashMap<String, HttpMeServlet> ServletHashMap = new HashMap<>();

    /**
     * 初始化
     * >加载web.xml的配置（Servlet）
     */
    public void init() {
        String basePath;
        try {
            basePath = MyTomcat.class.getResource("/").getPath();
            SAXReader reader = new SAXReader();

            Document document = reader.read(new File(basePath + "web.xml"));
            Element root = document.getRootElement();
            List<Element> childElements = root.elements();
            for (Element element : childElements) {
                if ("servlet".equalsIgnoreCase(element.getName())) {
                    Element servletName = element.element("servlet-name");
                    Element servletClass = element.element("servlet-class");
                    ServletHashMap.put(servletName.getText(),
                            (HttpMeServlet) Class.forName(servletClass.getText()).newInstance());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 运行的方法
     */
    public void start() {
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("服务启动，地址：http://localhost:8099");
            while (true) {
                Socket socket = serverSocket.accept();
                //输出socket
                System.out.println(socket);
                Thread thread = new SocketProcess(socket);
                thread.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 启动方法
     *
     * @param args
     */
    public static void main(String[] args) {
        MyTomcat myTomcat = new MyTomcat();
        myTomcat.init();
        myTomcat.start();
    }
}
